package cn.edu.zstu.qingzhu.qingzhushop.controller;

import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.provider.QiNiuProvider;
import cn.edu.zstu.qingzhu.qingzhushop.provider.UCloudProvider;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-07-31 15:42
 */
@RestController
@RequestMapping("/upload")
@Api(tags = "UCloud上传接口")
public class UCloudController {
    @Autowired
    private QiNiuProvider qiNiuProvider;
    @Autowired
    private UCloudProvider uCloudProvider;

    /**
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "图片上传",notes = "图片上传",consumes = "multipart/form-data",response = Object.class)
    @RequestMapping(value = "/image",method = {RequestMethod.POST}, headers = "content-type=multipart/form-data")
    public Object imageUpload(@ApiParam(value = "头像文件",type = "file",required = true)
                               @RequestParam("image") MultipartFile file){
        if(file.isEmpty()){
            return ResponseBean.error("无文件");
        }
        String fileName = UUID.randomUUID()+file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);
        try {
            String url=uCloudProvider.putStream(file.getInputStream(),file.getContentType(),fileName);
            return ResponseBean.ok("上传成功",url);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseBean.error("上传错误");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseBean.error("上传错误");
        }

    }
}
